package com.kabao.javafx.qq;

import com.kabao.javafx.qq.utils.ResourceUtils;
import javafx.animation.*;
import javafx.application.Application;
import javafx.application.ConditionalFeature;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;


public class JavaFxQqLoginApp extends Application {
    private double offsetX;
    private double offsetY;
    private Stage mainStage;
    private Stage primaryStage;

    //图片
    private List<Image> imageList = new ArrayList<>(260);
    private int index;

    private SystemTray systemTray;
    private TrayIcon trayIcon;

    @Override
    public void start(Stage primaryStage) throws Exception {
        //调用exit才退出
        Platform.setImplicitExit(false);
        this.primaryStage = primaryStage;
        initPrimaryStage(primaryStage);

        mainStage = new Stage(StageStyle.TRANSPARENT);
        mainStage.initOwner(primaryStage);

        for (int i = 13; i < 177; i++) {
            imageList.add(new Image(ResourceUtils.getResource("/img/loginframe/login" + i + ".png")));
        }
        //1.登录界面
        Pane loginPane = new Pane();
        String loginImage = ResourceUtils.getResource("/img/login-pane.png");
        ImageView iv1 = new ImageView(loginImage);
        Button settingBtn = new Button();
        settingBtn.setGraphic(new ImageView(ResourceUtils.getResource("/img/setting.png")));
        settingBtn.getStyleClass().add("btn");
        settingBtn.setLayoutX(338);
        settingBtn.setLayoutY(0);
        ImageView topImgV = new ImageView();
        loginPane.getChildren().add(iv1);
        DropShadow shadow = new DropShadow(8, new Color(0.0, 0.0, 0.0, 0.69));
        loginPane.getChildren().add(topImgV);
        loginPane.getChildren().add(settingBtn);

        //最小化按钮
        Button minBtn = new Button();
        minBtn.setGraphic(new ImageView(ResourceUtils.getResource("/img/mini.png")));
        minBtn.getStyleClass().add("btn");
        minBtn.setLayoutX(338 + 32);
        minBtn.setLayoutY(0);
        minBtn.setOnAction(actionEvent -> {
            mainStage.hide();
        });
        loginPane.getChildren().add(minBtn);

        //关闭按钮
        Button closeBtn = new Button();
        closeBtn.setGraphic(new ImageView(ResourceUtils.getResource("/img/close.png")));
        closeBtn.getStyleClass().add("close-btn");
        closeBtn.setLayoutX(338 + 32 + 26);
        closeBtn.setLayoutY(0);
        closeBtn.setOnAction(actionEvent -> {
            mainStage.hide();
            SwingUtilities.invokeLater(() -> {
                if (systemTray != null && trayIcon != null) {
                    systemTray.remove(trayIcon);
                }
            });
            Platform.exit();
            System.exit(0);
        });
        loginPane.getChildren().add(closeBtn);

        loginPane.setEffect(shadow);
        Timeline tl = new Timeline(new KeyFrame(Duration.millis(100), event -> {
            if (index == imageList.size() - 1) {
                index = 0;
            }
            topImgV.setImage(imageList.get(index++));
        }));
        tl.setCycleCount(Animation.INDEFINITE);
        tl.play();

        //2. 设置界面
        Pane settingPane = new Pane();
        String settingImage = ResourceUtils.getResource("/img/setting-pane.png");
        ImageView iv2 = new ImageView(settingImage);
        settingPane.getChildren().add(iv2);
        settingPane.setVisible(false);
        settingPane.setEffect(shadow);

        Button cancelBtn = new Button("取消");
        cancelBtn.getStyleClass().add("cancel-btn");
        cancelBtn.setLayoutX(331);
        cancelBtn.setLayoutY(299);
        settingPane.getChildren().add(cancelBtn);

        StackPane contentPane = new StackPane(settingPane, loginPane);
        BorderPane root = new BorderPane(contentPane);
        //设置边距,为了显示比边框阴影
        root.setPadding(new Insets(10));
        Scene scene = new Scene(root, null);
        //立体相机效果
        scene.setCamera(new PerspectiveCamera());
        scene.getStylesheets().add(ResourceUtils.getResource("/css/qq.css"));
        mainStage.setScene(scene);
        mainStage.show();

        //设置界面翻转
        settingBtn.setOnAction(actionEvent -> {
            flipAnim(settingPane, loginPane, true);
        });
        cancelBtn.setOnAction(actionEvent -> {
            flipAnim(loginPane, settingPane, false);
        });
        //设置拖动事件
        setDragStage(scene);
        //初始化系统托盘
        initTrayIcon();
    }

    private void initPrimaryStage(Stage primaryStage) {
        Scene scene1 = new Scene(new BorderPane(), 1, 1);
        scene1.getStylesheets().add(ResourceUtils.getResource("/css/qqtrayicon.css"));
        primaryStage.setScene(scene1);
        primaryStage.initStyle(StageStyle.UTILITY);
        primaryStage.setX(5000);
        primaryStage.show();
    }

    private void setDragStage(Scene scene) {
        scene.setOnMousePressed(event -> {
            offsetX = event.getSceneX();
            offsetY = event.getSceneY();
        });
        scene.setOnMouseDragged(event -> {
            mainStage.setX(event.getScreenX() - offsetX);
            mainStage.setY(event.getScreenY() - offsetY);
        });
    }

    private boolean fliping;

    private void initTrayIcon() {
        MenuItem openMenu = new MenuItem("", new Text("打开主面板"));
        openMenu.setOnAction(actionEvent -> {
            if (mainStage != null) {
                mainStage.show();
                mainStage.toFront();
            }
        });
        MenuItem exitMenu = new MenuItem("", new Text("退出"));
        exitMenu.setOnAction(event ->  {
            mainStage.hide();
            SwingUtilities.invokeLater(() -> {
                if (systemTray != null && trayIcon != null) {
                    systemTray.remove(trayIcon);
                }
            });
            Platform.exit();
            System.exit(0);
        });
        ContextMenu contextMenu = new ContextMenu(openMenu, new SeparatorMenuItem(), exitMenu);
        SwingUtilities.invokeLater(() -> {
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            if (!Platform.isSupported(ConditionalFeature.SWING)) {
                Platform.exit();
            }
            this.systemTray = SystemTray.getSystemTray();
            this.trayIcon = new TrayIcon(toolkit.getImage(getClass().getResource("/img/qq.png")), "QQ");
            try {
                systemTray.add(trayIcon);
            } catch (AWTException e) {
                e.printStackTrace();
            }
            //自适应托盘尺寸
            trayIcon.setImageAutoSize(true);
            trayIcon.addActionListener(e -> {
                Platform.runLater(() -> {
                    if (mainStage != null) {
                        mainStage.show();
                        mainStage.toFront();
                    }
                });
            });
            trayIcon.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent event) {
                    if (event.getButton() == MouseEvent.BUTTON3) {
                        Platform.runLater(() -> {
                            primaryStage.requestFocus();
                            //获取缩放比例
                            double scaleX = Screen.getPrimary().getOutputScaleX();
                            double scaleY = Screen.getPrimary().getOutputScaleY();
                            contextMenu.show(primaryStage, event.getXOnScreen() / scaleX + 8, event.getYOnScreen() / scaleY - 90);
                        });
                    }
                }
            });
        });
    }

    private void flipAnim(Pane showPane, Pane hidePane, boolean dir) {
        if (fliping) {
            return;
        }
        fliping = true;
        Duration duration = Duration.millis(500);
        //隐藏当前显示的页面
        RotateTransition hideRt = new RotateTransition(duration, hidePane);
        //反转轴
        hideRt.setAxis(Rotate.Y_AXIS);
        hideRt.setFromAngle(0);
        hideRt.setToAngle(dir ? 90 : -90);
        hideRt.setOnFinished(actionEvent -> {
            hidePane.setVisible(false);
            showPane.setVisible(true);
        });
        ScaleTransition hideSt = new ScaleTransition(duration, hidePane);
        hideSt.setFromX(1.0);
        hideSt.setToX(0.6);
        hideSt.setFromY(1.0);
        hideSt.setToY(0.6);

        ParallelTransition hideAnim = new ParallelTransition(hideRt, hideSt);


        //显示刚刚隐藏的页面
        RotateTransition showRt = new RotateTransition(duration, showPane);
        showRt.setAxis(Rotate.Y_AXIS);
        showRt.setFromAngle(dir ? -90 : 90);
        showRt.setToAngle(0);

        ScaleTransition showSt = new ScaleTransition(duration, showPane);
        showSt.setFromX(0.6);
        showSt.setToX(1.0);
        showSt.setFromY(0.6);
        showSt.setToY(1.0);

        ParallelTransition showAnim = new ParallelTransition(showSt, showRt);


        SequentialTransition st = new SequentialTransition(hideAnim, showAnim);
        st.setOnFinished(actionEvent -> fliping = false);
        st.play();
    }

    public static void main(String[] args) {
        launch(args);
    }
}